import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const bomId = searchParams.get('bomId')
    const category = searchParams.get('category')

    const where: any = {}
    if (bomId) where.bomId = bomId
    if (category) where.category = category

    const bomItems = await db.bOMItem.findMany({
      where,
      include: {
        bom: {
          select: { id: true, name: true, version: true }
        },
        supplier: {
          select: { id: true, name: true, code: true }
        }
      },
      orderBy: { createdAt: 'desc' }
    })

    return NextResponse.json(bomItems)
  } catch (error) {
    console.error('Error fetching BOM items:', error)
    return NextResponse.json(
      { error: 'Failed to fetch BOM items' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const {
      bomId,
      partNumber,
      name,
      description,
      category,
      quantity,
      unit,
      unitCost,
      supplierId,
      manufacturer,
      partNumberAlt,
      datasheet,
      lifecycle,
      leadTime,
      moq,
      mpq,
      location,
      notes
    } = body

    if (!bomId || !partNumber || !name || !quantity || !unit) {
      return NextResponse.json(
        { error: 'Missing required fields' },
        { status: 400 }
      )
    }

    // 计算总价
    const totalPrice = unitCost && quantity ? unitCost * quantity : null

    const bomItem = await db.bOMItem.create({
      data: {
        bomId,
        partNumber,
        name,
        description,
        category,
        quantity,
        unit,
        unitCost,
        totalPrice,
        supplierId,
        manufacturer,
        partNumberAlt,
        datasheet,
        lifecycle: lifecycle || 'ACTIVE',
        leadTime,
        moq,
        mpq,
        location,
        notes
      },
      include: {
        bom: {
          select: { id: true, name: true, version: true }
        },
        supplier: {
          select: { id: true, name: true, code: true }
        }
      }
    })

    return NextResponse.json(bomItem, { status: 201 })
  } catch (error) {
    console.error('Error creating BOM item:', error)
    return NextResponse.json(
      { error: 'Failed to create BOM item' },
      { status: 500 }
    )
  }
}